package com.zf.shuashua.advert.hot;

import android.app.Activity;
import android.view.View;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.advert.AdReportManager;
import com.zf.shuashua.advert.AdvertConstants;
import com.zf.shuashua.advert.ReportConstants;
import com.zf.shuashua.advert.TTAdManagerHolder;
import com.zf.shuashua.bean.AdvertReport;
import com.zf.shuashua.manager.ActionThirdReportManager;
import com.zf.shuashua.utils.UIUtils;
import com.zf.shuashua.utils.Util;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * 信息流广告-穿山甲
 */
public class NativeByteHotManager {

    private static final float WIDTH_DEFAULT = 270;
    private static final float HEIGHT_DEFAULT = (float) (WIDTH_DEFAULT / 1.78);
    private TTAdNative mTTAdNative;
    private String mAdvertType = AdvertConstants.NATIVE_TYPE_COMMON;
    private static NativeByteHotManager instance;
    private WeakReference<Activity> weakReference;
    private HotByteAdListener mListener;
    private String mCodeId = "945420044";
    private int count = 1;

    private float width = WIDTH_DEFAULT;
    private float height = HEIGHT_DEFAULT;

    private NativeByteHotManager() { }

    public static NativeByteHotManager getInstance() {
        if (null == instance) {
            synchronized (NativeByteHotManager.class) {
                if (null == instance) {
                    instance = new NativeByteHotManager();
                }
            }
        }
        return instance;
    }

    /**
     * 宽度占满
     * @param activity
     * @param advertType
     * @param listener
     */
    public void loadFullExpressAd(Activity activity,  String advertType, String codeId, int count, HotByteAdListener listener){
        mAdvertType = advertType;
        mCodeId = codeId;

        // this.width = UIUtils.getScreenWidthDp(activity) - 30;
        this.width = UIUtils.getScreenWidthDp(activity);
        this.height = (float) (width / 1.78);
        this.count = count;

        loadExpressAd(activity,listener);
    }

    private void loadExpressAd(Activity activity, HotByteAdListener listener){
        this.weakReference = new WeakReference<>(activity);
        if(mTTAdNative == null){
            setupSDK();
        }
        this.mListener = listener;
        loadExpressAd(mCodeId, width);
    }

    private void setupSDK(){
        TTAdManager ttAdManager = TTAdManagerHolder.get();
        mTTAdNative = ttAdManager.createAdNative(ShuaApplication.getContext());
    }

    private String uuiThirdAdvert;

    private void loadExpressAd(String codeId, float width) {
        uuiThirdAdvert = Util.getUUID32();
        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(codeId) //广告位id
                .setSupportDeepLink(true)
                .setAdCount(count) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(width, height) //期望模板广告view的size,单位dp
                .build();
        //step5:请求广告，对请求回调的广告作渲染处理
        mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
//                mExpressContainer.removeAllViews();
                weakReference.get().runOnUiThread(() -> {
                    if(mListener != null){
                        mListener.onError(code, message);
                    }
                });
                reportRequestFail(code + "", message);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads == null || ads.size() == 0){
                    return;
                }
                for (TTNativeExpressAd mTTAd: ads) {
                    bindAdListener(mTTAd);
                    mTTAd.render();
                }
                if(mListener != null){
                    mListener.onADLoaded(ads);
                }
                reportRequestSucc(ads.size());
            }
        });
        reportRequestStart();
    }

    private void reportRequestStart(){
        ActionThirdReportManager.getInstance().reportRequestStart(1, 4, mCodeId, count);
    }

    private void reportRequestSucc(int return_num) {
        ActionThirdReportManager.getInstance().reportRequestSucc(1, 4, mCodeId, return_num);
    }

    private void reportRequestFail(String error_code, String error_msg){
        ActionThirdReportManager.getInstance().reportRequestFail(1, 4, mCodeId, count, error_code, error_msg);
    }

    private void reportRequestRend(String error_code, String error_msg){
        ActionThirdReportManager.getInstance().reportRequestRend(1, 4, mCodeId, error_code, error_msg);
    }

    private long startTime = 0;

    private boolean mHasShowDownloadActive = false;

    private void bindAdListener(TTNativeExpressAd ad) {
        String planId = System.identityHashCode(ad) + "";
        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
            @Override
            public void onAdClicked(View view, int type) {
//                TToast.show(mContext, "广告被点击");
                AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.ImageClick, getReportType());
            }

            @Override
            public void onAdShow(View view, int type) {
//                TToast.show(mContext, "广告展示");
                AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.ImageShow, getReportType());
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
//                Log.e("ExpressView","render fail:"+(System.currentTimeMillis() - startTime));
//                TToast.show(mContext, msg+" code:"+code);
//                weakReference.get().runOnUiThread(() -> {
//                    if(mListener != null){
//                        mListener.onError();
//                    }
//                });
                reportRequestRend(code +"", msg);
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
//                Log.e("ExpressView","render suc:"+(System.currentTimeMillis() - startTime));
                //返回view的宽高 单位 dp
//                TToast.show(mContext, "渲染成功");
//                mExpressContainer.removeAllViews();
//                mExpressContainer.addView(view);
//                if(mListener != null){
//                    mListener.onRenderSuccess(view);
//                }
            }
        });
        //dislike设置
//        bindDislike(ad, false);
        if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD){
            return;
        }
        ad.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() {
//                TToast.show(NativeExpressActivity.this, "点击开始下载", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                if (!mHasShowDownloadActive) {
                    mHasShowDownloadActive = true;
//                    TToast.show(NativeExpressActivity.this, "下载中，点击暂停", Toast.LENGTH_LONG);
                }
            }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
//                TToast.show(NativeExpressActivity.this, "下载暂停，点击继续", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
//                TToast.show(NativeExpressActivity.this, "下载失败，点击重新下载", Toast.LENGTH_LONG);
            }

            @Override
            public void onInstalled(String fileName, String appName) {
//                TToast.show(NativeExpressActivity.this, "安装完成，点击图片打开", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
//                TToast.show(NativeExpressActivity.this, "点击安装", Toast.LENGTH_LONG);
            }
        });
    }

    //设置广告的不喜欢，注意：强烈建议设置该逻辑，如果不设置dislike处理逻辑，则模板广告中的 dislike区域不响应dislike事件。
//    private void bindDislike(TTNativeExpressAd ad, boolean customStyle) {
//        if (customStyle) {
//            //使用自定义样式
//            List<FilterWord> words = ad.getFilterWords();
//            if (words == null || words.isEmpty()) {
//                return;
//            }
//
//            final DislikeDialog dislikeDialog = new DislikeDialog(this, words);
//            dislikeDialog.setOnDislikeItemClick(new DislikeDialog.OnDislikeItemClick() {
//                @Override
//                public void onItemClick(FilterWord filterWord) {
//                    //屏蔽广告
////                    TToast.show(mContext, "点击 " + filterWord.getName());
//                    //用户选择不喜欢原因后，移除广告展示
//                    mExpressContainer.removeAllViews();
//                }
//            });
//            ad.setDislikeDialog(dislikeDialog);
//            return;
//        }
//        //使用默认模板中默认dislike弹出样式
//        ad.setDislikeCallback(NativeExpressActivity.this, new TTAdDislike.DislikeInteractionCallback() {
//            @Override
//            public void onSelected(int position, String value) {
////                TToast.show(mContext, "点击 " + value);
//                //用户选择不喜欢原因后，移除广告展示
//                mExpressContainer.removeAllViews();
//            }
//
//            @Override
//            public void onCancel() {
////                TToast.show(mContext, "点击取消 ");
//            }
//        });
//    }

    private String getReportType(){
        String type = ReportConstants.NATIVE_TYPE_COMMON;
        switch (mAdvertType) {
            case AdvertConstants.NATIVE_TYPE_COMMON:
                type = ReportConstants.NATIVE_TYPE_COMMON;
                break;
            case AdvertConstants.NATIVE_TYPE_BUBBLE:
                type = ReportConstants.NATIVE_TYPE_BUBBLE;
                break;
            case AdvertConstants.NATIVE_TYPE_ENCOURAGE:
                type = ReportConstants.NATIVE_TYPE_ENCOURAGE;
                break;
            case AdvertConstants.NATIVE_TYPE_WITHDRAW:
                type = ReportConstants.NATIVE_TYPE_WITHDRAW;
                break;
        }
        return type;
    }

    private String getCodeId(){
        String codeId = "945172865";
        switch (mAdvertType) {
            case AdvertConstants.NATIVE_TYPE_COMMON:
                codeId = "945172865";
                break;
            case AdvertConstants.NATIVE_TYPE_BUBBLE:
                codeId = "945172862";
                break;
            case AdvertConstants.NATIVE_TYPE_ENCOURAGE:
//                codeId ="945303192";
                codeId ="945172860";
                break;
            case AdvertConstants.NATIVE_TYPE_WITHDRAW:
                codeId ="945172864";
                break;
            case AdvertConstants.NATIVE_TYPE_HOT:
                codeId ="945420044";
                break;
        }
        return codeId;
    }

}
